package com.drcoffee.drcoffeemall.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
@Slf4j
class DataBackupTask {
    final
    private static String remoteHostCN = "112.124.8.150";
    final
    private static String remoteHostEN = "8.208.90.100";
    final
    private static int remotePort = 3306;
    final
    private static String databaseName = "parts_mall";
    final
    private static String username = "root";
    final
    private static String password = "dr230508";

    @Scheduled(cron = "0 0 10 * * ?")
    public void backupTaskCN() {
        dataBackup(remoteHostCN, 1);
    }

    @Scheduled(cron = "0 0 10 * * ?")
    public void backupTaskEN() {
        dataBackup(remoteHostEN, 2);
    }

    public static void dataBackup(String remoteHost, Integer sort) {
        log.info("⏰ 😎 START-TASK：数据库备份.");
        String[] command = {
                "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe",
//                "/usr/local/mysql/bin/mysqldump",
                "-h", remoteHost,
                "-P", String.valueOf(remotePort),
                "-u", username,
                "-p" + password,
                databaseName
        };
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
        String formattedDateTime = currentDateTime.format(formatter);
        String backupPath = "";
        String pathBefore = "D:/Application Document/Parts Mall/DataBackup/";
        if (sort == 1) {
//            backupPath = "D:/ApplicationJar/PMALL/DataBackup/CN/" + formattedDateTime + "_parts_mall.sql";
            backupPath = pathBefore + "CN/" + formattedDateTime + "_parts_mall.sql";
        } else {
//            backupPath = "D:/ApplicationJar/PMALL/DataBackup/EN/" + formattedDateTime + "_parts_mall.sql";
            backupPath = pathBefore + "EN/" + formattedDateTime + "_parts_mall.sql";
        }
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        File backupFile = new File(backupPath);
        processBuilder.redirectOutput(backupFile);
        try {
            Process process = processBuilder.start();
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("⏰ 😍 SUCCESS-TASK：数据库备份成功，备份文件保存在: " + backupPath);
            } else {
                log.info("⏰ 😭 ERROR-TASK：数据库备份失败.");
            }
        } catch (Exception e) {
            log.error("⏰ 🤬 END-TASK-EXCEPTION：数据备份异常：" + e.getMessage());
            e.printStackTrace();
        }

    }


}
